import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-stock-flow',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './stock-flow.component.html',
  styleUrls: ['./stock-flow.component.scss']
})
export class StockFlowComponent implements OnInit {
  mergedWarehouseList: any[] = [];
  loading = false;
  error: string | null = null;
  pageIndex = 1;
  pageSize = 5;
  pagedList: any[] = [];
  search = {
    estimatedArrivalStart: '',
    estimatedArrivalEnd: '',
    purchaseOrderNo: '',
    status: '',
    transportCompany: '',
    supplier: '',
    orderType: ''
  };
  filteredList: any[] = [];
  stats = {
    totalOrderCount: 0,
    inOrderCount: 0,
    outOrderCount: 0,
    inCount: 0,
    inAmount: 0,
    outCount: 0,
    outAmount: 0
  };
  constructor(private http: HttpClient) {}
  ngOnInit(): void {
    this.loading = true;
    this.http.get<any[]>('https://localhost:44359/api/app/merged-warehouse/all').subscribe({
      next: (res) => {
        // 模拟部分数据的otherwarehousingEstimatedArrivalTime字段
        const mockTimes = [
          '2024-07-08 10:00:00',
          '2024-07-09 14:30:00',
          '2024-07-10 09:15:00',
          '2024-07-11 16:45:00',
          '2024-07-12 08:20:00'
        ];
        res.forEach((item, idx) => {
          if (idx < mockTimes.length) {
            item.otherwarehousingEstimatedArrivalTime = mockTimes[idx];
          }
        });
        this.mergedWarehouseList = res;
        this.filteredList = res;
        this.loading = false;
        this.error = null;
        this.updatePagedList();
        this.updateStats(res);
      },
      error: (err) => {
        this.loading = false;
        this.error = '数据加载失败：' + (err?.message || err?.statusText || '未知错误');
      }
    });
  }

  onSearch() {
    let filtered = this.mergedWarehouseList;
    if (this.search.estimatedArrivalStart) {
      filtered = filtered.filter(x => x.customergoodsEstimatedArrivalTime && x.customergoodsEstimatedArrivalTime >= this.search.estimatedArrivalStart);
    }
    if (this.search.estimatedArrivalEnd) {
      filtered = filtered.filter(x => x.customergoodsEstimatedArrivalTime && x.customergoodsEstimatedArrivalTime <= this.search.estimatedArrivalEnd);
    }
    if (this.search.purchaseOrderNo) {
      filtered = filtered.filter(x => x.customergoodsPurchaseOrderNo && x.customergoodsPurchaseOrderNo.includes(this.search.purchaseOrderNo));
    }
    if (this.search.status) {
      filtered = filtered.filter(x => x.customergoodsStatus === this.search.status);
    }
    if (this.search.transportCompany) {
      filtered = filtered.filter(x => x.customergoodsTransportCompany === this.search.transportCompany);
    }
    if (this.search.supplier) {
      filtered = filtered.filter(x => x.customergoodsSupplier && x.customergoodsSupplier.includes(this.search.supplier));
    }
    if (this.search.orderType) {
      filtered = filtered.filter(x => String(x.customergoodsOrderType) === this.search.orderType);
    }
    this.pageIndex = 1;
    this.pagedList = filtered.slice(0, this.pageSize);
    this.filteredList = filtered;
    this.updateStats(filtered);
  }

  onReset() {
    this.search = {
      estimatedArrivalStart: '',
      estimatedArrivalEnd: '',
      purchaseOrderNo: '',
      status: '',
      transportCompany: '',
      supplier: '',
      orderType: ''
    };
    this.pageIndex = 1;
    this.filteredList = this.mergedWarehouseList;
    this.updatePagedList();
    this.updateStats(this.mergedWarehouseList);
  }

  updatePagedList() {
    const start = (this.pageIndex - 1) * this.pageSize;
    const list = this.filteredList.length ? this.filteredList : this.mergedWarehouseList;
    this.pagedList = list.slice(start, start + this.pageSize);
    this.updateStats(list);
  }

  onPageSizeChange(event: any) {
    this.pageIndex = 1;
    this.updatePagedList();
  }

  prevPage() {
    if (this.pageIndex > 1) {
      this.pageIndex--;
      this.updatePagedList();
    }
  }

  nextPage() {
    const list = this.filteredList.length ? this.filteredList : this.mergedWarehouseList;
    if (this.pageIndex * this.pageSize < list.length) {
      this.pageIndex++;
      this.updatePagedList();
    }
  }

  updateStats(list: any[]) {
    this.stats.totalOrderCount = list.length;
    this.stats.inOrderCount = list.filter(x => x.customergoodsStatus === '已入库').length;
    this.stats.outOrderCount = list.filter(x => x.customergoodsStatus === '已出库').length;
    this.stats.inCount = list.filter(x => x.customergoodsStatus === '已入库').length; // 示例：可替换为实际字段
    this.stats.inAmount = list.filter(x => x.customergoodsStatus === '已入库').reduce((sum, x) => sum + (Number(x.inAmount) || 0), 0);
    this.stats.outCount = list.filter(x => x.customergoodsStatus === '已出库').length; // 示例：可替换为实际字段
    this.stats.outAmount = list.filter(x => x.customergoodsStatus === '已出库').reduce((sum, x) => sum + (Number(x.outAmount) || 0), 0);
  }
}
